package com.briup.pts.service.impl;

import com.briup.pts.config.exception.ServiceException;
import com.briup.pts.config.response.ResultCode;
import com.briup.pts.domain.bean.Animal;
import com.briup.pts.domain.bean.IndexRecord;
import com.briup.pts.mapper.AnimalMapper;
import com.briup.pts.mapper.IndexRecordMapper;
import com.briup.pts.service.IndexRecordService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
@RequiredArgsConstructor
public class IndexRecordServiceImpl implements IndexRecordService {

    private final IndexRecordMapper mapper;
    private final AnimalMapper animalMapper;

    @Override
    public PageInfo<IndexRecord> pageQuery(Integer pageNum, Integer pageSize,
                                           Integer startWeight, Integer endWeight) {
        try (Page<IndexRecord> ignore = PageHelper.startPage(pageNum, pageSize)){
            // 根据条件查询数据
            List<IndexRecord> indexRecords = mapper.queryByConditional(
                    startWeight, endWeight);
            Page<IndexRecord> page = (Page<IndexRecord>) indexRecords;
            // 创建分页信息对象，并返回数据
            return new PageInfo<>(page);
        }
    }

    // 在方法上添加@Transactional注解，那么spring框架就会对该方法进行事物管理
    @Transactional
    @Override
    public void saveOrUpdate(IndexRecord indexRecord) {
        // 根据id是否传入判断是修改还是新增
        if (indexRecord.getIrdId() != null){
            // 说明是新增，但是根据实际的业务情况，更新操作不合理，直接抛出异常
            throw new ServiceException(ResultCode
                    .INDEX_RECORD_MODIFIED_IS_NOT_SUPPORT);
        }
        // 如果id为null，说明是新增操作
        // 在新增指标之前，应该确定该动物是否存在
        Animal animal = animalMapper.queryByIdWithStatus(indexRecord.getIrdAnimalId(),"养殖中");
        if (animal == null){
            throw new ServiceException(ResultCode.ANIMAL_IS_NOT_EXISTS);
        }
        // 确定该动物在指定的时间点中是否已经记录过指标数据
        IndexRecord record = mapper.queryByTime(indexRecord.getIrdAnimalId(),
                indexRecord.getIrdTime());
        if (record != null){
            throw new ServiceException(ResultCode.INDEX_RECORD_IS_EXISTS);
        }
        // 新增指标数据
        mapper.insertIndexRecord(indexRecord);
        // 将动物相关的指标数据同步修改到动物表中
        animal.setAWeight(indexRecord.getIrdWeight());
        animal.setAHealthy(indexRecord.getIrdHealthy());
        animalMapper.updateAnimal(animal);
    }

    @Override
    public void deleteBatch(List<String> irdIds) {
        if (CollectionUtils.isEmpty(irdIds)){
            return;
        }
        // 删除数据
        mapper.deleteBatch(irdIds);
    }
}
